import AsyncStorage from '@react-native-async-storage/async-storage';
import en from '../local/en.json';
import zhHK from '../local/zh_hk.json';
import {conType, progressStatus} from '../constants';

// 语言文件
const localizations: Record<string, any> = {
  en,
  zhHK,
  // 更多语言...
};

/** 多语言处理 */
export const t = (
  language: string,
  key: string,
  options?: Record<string, any>,
) => {
  let text: string = localizations[language][key];
  if (!text) return key;
  if (options && typeof options === 'object') {
    Object.keys(options).forEach(k => {
      text = text.replace(`{{${k}}}`, options[k]);
    });
    return text;
  }
  return text;
};

/**
 * 数字处理
 * @param n 要格式化的数字
 * @param t 格式化的类型
 * @returns {number}
 */
export const dight = (n: number, t = 'w') => {
  if (t === 'w') {
    return Number((n / 10000).toFixed(1));
  }
  return n;
};

/**
 * 内容状态: 连载中、已完结
 * @param info
 * @returns
 */
export const contextStatus = (info: any) => {
  const obj = {tKey: '', tOptions: {}};
  if (info?.Status === 2) {
    obj.tKey = 'finished';
  } else if (info?.Status === 1) {
    if (info?.Type === 1) {
      obj.tKey = 'updatedToC';
      obj.tOptions = {count: info.ChapterCount};
    } else if (info?.Type === 2) {
      obj.tKey = 'updatedToS';
      obj.tOptions = {count: info.ChapterCount};
    }
  }
  return obj;
};

// 获取当前内容的状态 连载中|已完结
export const getConStatus = (stuates: 1 | 2) => progressStatus[stuates];

/** 获取是章|话 */
export const getSumChap = (type: 1 | 2) => conType[type];

/**
 * 设置本地存贮值
 * @param key 存贮的键
 * @param data 存贮的值
 */
export const setItem = (key: string, data: any) =>
  AsyncStorage.setItem(key, JSON.stringify(data));

/**
 * 获取本地存贮值
 * @param key 获取本地值的键
 */
export const getItem = async (key: string) => {
  const data = await AsyncStorage.getItem(key);
  if (data) return JSON.parse(data);
  return '';
};

/**
 * 删除本地存贮
 * @param key 本地存贮值的键
 */
export const removeItem = (key: string) => AsyncStorage.removeItem(key);

export const lsClear = () => AsyncStorage.clear();

export const fillZero = (n: number) => {
  if (n > 9) return n;
  return `0${n}`;
};

/** 获取时间年-月 */
export const getYM = (t: string) =>
  `${fillZero(new Date(t).getFullYear())}-${fillZero(
    new Date(t).getMonth() + 1,
  )}`;

/** 获取时间月-日 */
export const getMD = (t: string) =>
  `${fillZero(new Date(t).getMonth() + 1)}-${fillZero(new Date(t).getDate())}`;
